import { isBoolean } from 'lodash-es';

import type { PaginationProps } from '../types/pagination';

import { getViewportOffset } from '@/utils/dom-utils';

export function useTableHeight(
  tableElRef: ComponentRef,
  pagination: ComputedRef<boolean | PaginationProps>,
  maxHeight: number | null,
  resizeHeightOffset = 0,
) {
  let paginationEl: HTMLElement | null;
  const deviceHeight = ref(150);

  async function computeTableHeight() {
    const table = unref(tableElRef);
    if (!table) {
      return;
    }

    // if (!unref(getCanResize)) {
    //   return;
    // }
    const tableEl: any = table?.$el;
    const headEl = tableEl.querySelector('.n-data-table-thead ');
    const { bottomIncludeBody } = getViewportOffset(headEl);
    const headerH = 64;
    let paginationH = 2;
    const marginH = 24;
    if (!isBoolean(unref(pagination))) {
      paginationEl = tableEl.querySelector('.n-data-table__pagination') as HTMLElement;
      if (paginationEl) {
        const offsetHeight = paginationEl.offsetHeight;
        paginationH += offsetHeight || 0;
      } else {
        paginationH += 28;
      }
    }
    let height
      = bottomIncludeBody - (headerH + paginationH + marginH + (resizeHeightOffset || 0));
    height = maxHeight && maxHeight < height ? maxHeight : height;
    deviceHeight.value = height;
    return height;
  }

  return {
    computeTableHeight,
    deviceHeight,
  };
}
